package isi_ib;

import java.sql.ResultSet;
import java.sql.SQLException;

import utiles_isi.isi_conexion;
import utiles_isi.isi_util;

import com.ib.client.Contract;
import com.ib.client.EClientSocket;
import com.ib.client.Order;
import com.ib.client.OrderState;
/*
 * 
 *   String m_orderType   MKT,MKTCLS, LMT, LMTCLS,PEGMKT, SCALE,STP, STPLMT,TRAIL,REL,VWAP,TRAILLIMIT
 *   String String m_action  BUY, SELL, SSHORT
 *   double m_lmtPrice --> LMT,STPLMT ... default debe ser 0
 *   double m_auxPrice ---> STP,STPLMT ... default debe ser 0
 *   String m_tif ---> DAY, GTC, IOC, GTD
 *   bool m_transmit ---> false se crea pero no se trasmite
 *   
 *   
 *   int m_parentId interesante para braket orders
 *   
 */

public class MyOrder {
		public Order order;
		public MyContract mycontract;
		private isi_conexion conexion;
		
		
		public MyOrder(int orderId,MyContract mc_){
			conexion=null;
			order = new Order();
			order.m_orderId=orderId;
			if(mc_==null)mycontract=new MyContract("","ES");
			else mycontract=mc_;
			}
		 
/* Guarda Orden SQL
 * 
 * 
 * 
 * 
 * 		
 */
	    
		public void setConexion(isi_conexion conexion_){
			conexion=conexion_;
			
		}
		public boolean conectaSQL()
		{
			if(conexion==null) conexion= new isi_conexion("");
			if(!conexion.Active()) conexion.conecta();
			return conexion.Active();
		}
		public boolean desConectaSQL()
		{
			boolean ret_=false;
			if(conexion!=null){
				conexion.desconecta();
				ret_=conexion.Active();
			}
			return ret_;
		}
		
		public void GuardaStatus(int orderId, String status, int filled,
				int remaining, double avgFillPrice, int permId, int parentId,
				double lastFillPrice, int clientId, String whyHeld){
			
			String sql_="";
			conectaSQL();
			try {
			if(conexion!=null)  { 
				sql_="UPDATE isitrader.orders SET " +
						"status='" +status+
						"',filled='"+String.valueOf(filled)+
						"',remaining='"+String.valueOf(remaining)+
						"',avgFillPrice='"+String.valueOf(avgFillPrice)+
						"',permId='"+String.valueOf(permId)+
						"',parentId='"+String.valueOf(parentId)+
						"',lastFillPrice='"+String.valueOf(lastFillPrice)+
						"',clientId='"+String.valueOf(clientId)+
						"',whyHeld='"+whyHeld+
						"',EXEC_DATE=now() WHERE ORDERID="+String.valueOf(orderId)+";";
				conexion.st.execute(sql_);
						
			}
			}catch (SQLException e) {e.printStackTrace();}
			
			
		}
		
		public void GuardaOrderState(int rderId_,OrderState OrderState_){
			String sql_="";
			conectaSQL();
			try {
			if(conexion!=null)  { 
				sql_="REPLACE INTO isitrader.orderstate SET " +
						"ORDERID='" +String.valueOf(rderId_)+
						"',m_commission='"+String.valueOf(OrderState_.m_commission)+
						"',m_commissionCurrency='"+OrderState_.m_commissionCurrency+
						"',m_equityWithLoan='"+OrderState_.m_equityWithLoan+
						"',m_initMargin='"+OrderState_.m_initMargin+
						"',m_maxCommission='"+String.valueOf(OrderState_.m_maxCommission)+
						"',m_minCommission='"+String.valueOf(OrderState_.m_minCommission)+
						"',m_status='"+OrderState_.m_status+
						"',m_warningText='"+OrderState_.m_warningText+
						"',fecha=now()";
				conexion.st.execute(sql_);
						
			}
			}catch (SQLException e) {e.printStackTrace();}
			
		}
		
		public String CargaOrder (int rderId_,Order order_,Contract Contract_){
			String sql_="select CONTRACT_SYMBOL,CONTRACT_SECTYPE,CONTRACT_EXPIRITY,ACTION,LMTPRICE,TOTALQUANTITY,status " +
					"from isitrader.orders where ORDERID=" + String.valueOf(rderId_);
			String status_="";
			if(conexion!=null){
				try {
					if(!conexion.Active()) conexion.conecta(); 
					ResultSet rs=conexion.st.executeQuery(sql_);
					while (rs.next()){
						order_.m_orderId=rderId_;
						 Contract_.m_symbol=rs.getString("CONTRACT_SYMBOL");
						 Contract_.m_secType=rs.getString("CONTRACT_SECTYPE");
						 Contract_.m_expiry=rs.getString("CONTRACT_EXPIRITY");
						 Contract_.m_expiry=rs.getString("CONTRACT_EXPIRITY");
						 order_.m_action=rs.getString("ACTION");
						 order_.m_orderType=rs.getString("ORDERTYPE");
						 order_.m_lmtPrice=isi_util.isiParseDouble(rs.getString("LMTPRICE"));
						 order_.m_totalQuantity=isi_util.isiParseInt(rs.getString("TOTALQUANTITY"));
						 status_=rs.getString("status");						
					}
					
				}catch (SQLException e) {e.printStackTrace();}
				
			}
			return status_;
		}
		
		
		
		public void GuardaOrder(Order order_,Contract Contract_,boolean init_){
			String sql_="";
			conectaSQL();
			if(conexion!=null)  { 
				   try {
					if(!conexion.Active()) conexion.conecta();   
					{
						
						sql_="REPLACE  INTO isitrader.orders set " +
							" ORDERID='"+String.valueOf(order_.m_orderId)+
							"',CONTRACT_SYMBOL='"+  Contract_.m_symbol +                           
							"',CONTRACT_SECTYPE='"+Contract_.m_secType+
							"',CONTRACT_EXPIRITY='"+Contract_.m_expiry+
							"',ACTION='"+order_.m_action +
							"',ORDERTYPE='"+order_.m_orderType+
							"',LMTPRICE='"+String.valueOf(order_.m_lmtPrice)+
							"',TOTALQUANTITY='"+String.valueOf(order_.m_totalQuantity)+
							(init_?"',ORDER_DATE=now();":"';");
						conexion.st.execute(sql_);
					}
				} catch (SQLException e) {
							e.printStackTrace();
				}
			   }
		}
		
		private void GuardaOrder(){	GuardaOrder(order,mycontract.contrato,true);	}

		public boolean PasaHoraCierre(){
			return PasaHoraCierre(mycontract.contrato);
		}
		public boolean PasaHoraCierre(Contract Contract_){
			String sql_="select isitrader.F_fin_horario('"+Contract_.m_symbol+"') AS C;";
			int ret_=0;
			conectaSQL();
			if(conexion!=null){
				try {
					if(!conexion.Active()) conexion.conecta(); 
					ResultSet rs=conexion.st.executeQuery(sql_);
					while (rs.next()){
								ret_=isi_util.isiParseInt(rs.getString("C"));
								
						
					}
					
				}catch (SQLException e) {e.printStackTrace();}
				
			}
			return (ret_==1);
			
		}
		
		/*FIN GUARDA ORDER SQL
 * 
 * 
 */
		
		
		
		/// Ordenes /////////////
		public void SetTransmit(boolean tr_){
			order.m_transmit = tr_;
		}
		public boolean GetTransmit(){
			return order.m_transmit ;
		}
		public void SetOrderId(int ord_){
			order.m_orderId=ord_;
		}
		public int GetOrderId(){
			return order.m_orderId;
		}
		/// Ordenes /////////////
		
		
		public void CompraVende(String action,String orderType,int totalQuantity,double lmtPrice,double auxPrice ){
			order.m_action=action;
			order.m_orderType=orderType;
			order.m_lmtPrice=lmtPrice;
			order.m_auxPrice=auxPrice;
			order.m_totalQuantity=totalQuantity;
		}
		public void CompraMercado(int totalQuantity){
			CompraVende("BUY","MKT",totalQuantity,0,0 );	
		}
		public void CompraLimit(int totalQuantity,double lmtPrice){
			CompraVende("BUY","LMT",totalQuantity,lmtPrice,0 );	
		}
		public void CompraStop(int totalQuantity,double lmtPrice,double auxPrice){
			CompraVende("BUY","STP",totalQuantity,lmtPrice,auxPrice );	
		}

		public void VendeMercado(int totalQuantity){
			CompraVende("SELL","MKT",totalQuantity,0,0 );	
		}
		public void VendeLimit(int totalQuantity,double lmtPrice){
			CompraVende("SELL","LMT",totalQuantity,lmtPrice,0 );	
		}
		public void VendeStop(int totalQuantity,double lmtPrice,double auxPrice){
			CompraVende("SELL","STP",totalQuantity,lmtPrice,auxPrice );	
		}
		//// exec
		public void reqIDs(EClientSocket   m_client_){
	    	if(m_client_!=null)   	m_client_.reqIds(1);
	    }
		public void Open(EClientSocket   m_client_){
			if(m_client_!=null)
			{
				GuardaOrder();
				m_client_.placeOrder(order.m_orderId, mycontract.contrato, order);
			}
		}
		
		public void Cancel(EClientSocket   m_client_){
			if(m_client_!=null)
			m_client_.cancelOrder(order.m_orderId);
		}
		//////
		

}
